from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response
from models import MainWord, DefinitionPartOfSpeech, WordUsage

MAX_QUERY_STR_LEN = 40

# -----------------------------------------------------------------------------
def search_form(request):
    """
    obsolete - 'search' now handles everything.
    """
    return render_to_response('search_form.html')

# -----------------------------------------------------------------------------
def search(request):
    message = ""

    context = {"value_entered":False, "errors":[]}

    if 'q' in request.GET:
        context["value_entered"] = True
        q = request.GET['q']
        if not q:
            context["errors"].append("Please input word.")
        elif len(q) > MAX_QUERY_STR_LEN :
            context["errors"].append("Query string too long (max: %d characters)" % MAX_QUERY_STR_LEN)
        else:
            # words = MainWord.objects.filter(word__icontains=q)
            words = WordUsage.objects.filter(part_of_speech_fk__word_fk__word__icontains=q)

            message += 'You searched for: %r' % request.GET['q']

            values = request.GET.items()
            values.sort()
            context.update(
                {"title":"Search result",
                 "query":q,
                 "words":words} )
            assert context["value_entered"]

    return render_to_response("search_results.html", context)

